package com.bestcem.xm.qdes.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bestcem.xm.common.core.annotation.XmGet;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.mybatis.base.ResultPage;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.qdes.controller.param.CreateMessageParam;
import com.bestcem.xm.qdes.controller.param.MessagePageParam;
import com.bestcem.xm.qdes.controller.vo.DeletedCountVo;
import com.bestcem.xm.qdes.controller.vo.OnlyIdVo;
import com.bestcem.xm.qdes.entity.MessageTemplate;
import com.bestcem.xm.qdes.enums.MessageTemplateStatusEnum;
import com.bestcem.xm.qdes.enums.MessageTemplateUsageEnum;
import com.bestcem.xm.qdes.grpc.client.UserGrpcClient;
import com.bestcem.xm.qdes.grpc.client.dto.UserDto;
import com.bestcem.xm.qdes.service.MessageService;
import com.bestcem.xm.qdes.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Objects;

/**
 * @author xiaoshu.shao <xiaoshu.shao@idiaoyan.com>
 * @version V1.0
 * @date 2022/8/1
 */
@Slf4j
@Api(tags = "模板库-消息库")
@RestController
@RequiredArgsConstructor
@RequestMapping("/message")
public class MessageController {

    private @NonNull MessageService messageService;

    private @NonNull UserGrpcClient userGrpcClient;

    /**
     * 创建 MessageTemplate
     *
     * @param param
     * @return
     */
    @ApiOperation(value = "创建消息模板")
    @PostMapping("/messagetemplate")
    public XmResultJson<OnlyIdVo> createMessageTemplate(@Validated @RequestBody CreateMessageParam param) {
        /*XmResultJson check = checkCreateMessageParam(param);
        if (!check.isSuccess()) {
            return check;
        }*/
        String userId = SecurityContextHolder.getUserId();
        MessageTemplate messagetemplate = new MessageTemplate();
        BeanUtils.copyProperties(param, messagetemplate, new String[]{"id"});
        messagetemplate.setOrgId(SecurityContextHolder.getOrgId());
        if (Objects.isNull(messagetemplate.getStatus())) {
            messagetemplate.setStatus(MessageTemplateStatusEnum.CHECKING.getIndex());
        }
        if (Objects.isNull(messagetemplate.getUseStatus())) {
            messagetemplate.setUseStatus(MessageTemplateUsageEnum.USE.getIndex());
        }
        if (Objects.isNull(messagetemplate.getIsDefault())) {
            messagetemplate.setIsDefault(Boolean.FALSE);
        }
        messagetemplate.setCreatorId(userId);
        messagetemplate.setCreator(userId);
        messageService.saveOrUpdate(messagetemplate);
        OnlyIdVo data = new OnlyIdVo();
        data.setId(messagetemplate.getId());
        return XmResultJson.success(data);
    }


    /**
     * MessageTemplate 详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "消息模板详情")
    @GetMapping("/messagetemplate/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<MessageTemplate> getMessageTemplate(@PathVariable String id) {
        MessageTemplate messagetemplate = messageService.getById(id);
        if (StrUtil.isBlankIfStr(messagetemplate.getCreatorId())) {
            messagetemplate.setCreator("超级管理员");
        } else {
            UserDto user = userGrpcClient.getUser(messagetemplate.getCreatorId());
            messagetemplate.setCreator(user.getName());
        }
        return XmResultJson.success(messagetemplate);
    }

    @ApiOperation(value = "默认模板")
    @GetMapping("/default/messagetemplate/")
    public XmResultJson<List<MessageTemplate>> getDefaultMessageTemplate(@RequestParam("ttype") Integer ttype, @RequestParam("scenario") Integer scenario) {
        LambdaQueryWrapper<MessageTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MessageTemplate::getTtype, ttype);
        wrapper.eq(MessageTemplate::getScenario, scenario);
        wrapper.eq(MessageTemplate::getOrgId, SecurityContextHolder.getOrgId());
        wrapper.eq(MessageTemplate::getDefaultTemplate, "默认模板");
        List<MessageTemplate> messagetemplate = messageService.list(wrapper);
        return XmResultJson.success(messagetemplate);
    }

    /**
     * 更新 MessageTemplate
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "更新消息模板")
    @PutMapping("/messagetemplate/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<OnlyIdVo> updateMessageTemplate(@PathVariable String id, @Validated @RequestBody CreateMessageParam param) {
        /*XmResultJson check = checkCreateMessageParam(param);
        if (!check.isSuccess()) {
            return check;
        }*/
        MessageTemplate messagetemplate = messageService.getById(id);
        if (Objects.isNull(messagetemplate)) {
            return XmResultJson.fail(-1, "template[id={" + id + "}] not found");
        }
        BeanUtils.copyProperties(param, messagetemplate);
        messagetemplate.setId(id);
        messagetemplate.setUpdatedId(SecurityContextHolder.getUserId());
        messageService.saveOrUpdate(messagetemplate);
        OnlyIdVo data = new OnlyIdVo();
        data.setId(id);
        return XmResultJson.success(data);
    }

    /**
     * 删除 MessageTemplate
     *
     * @return
     */
    @ApiOperation(value = "删除消息模板")
    @DeleteMapping("/messagetemplate/{id:[a-fA-F0-9]{24}}")
    public XmResultJson<DeletedCountVo> deleteMessageTemplate(@PathVariable String id) {
        boolean isDeleted = messageService.removeByIds(ListUtil.of(id));
        if (isDeleted) {
            DeletedCountVo data = new DeletedCountVo();
            data.setDeletedCount(1);
            return XmResultJson.success(data);
        }
        return XmResultJson.fail(-1, "template[id={" + id + "}] not found");
    }

    /**
     * MessageTemplate 查询列表
     *
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "page", value = "页码"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "rowsPerPage", value = "每页条数")
    })
    @ApiOperation(value = "消息模板查询列表")
    @GetMapping("/messagetemplate")
    public XmResultJson<ResultPage<MessageTemplate>> getMessageTemplate(@ApiIgnore Page<MessageTemplate> page, @XmGet MessagePageParam param) {
        LambdaQueryWrapper<MessageTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!Objects.isNull(param.getScenario()), MessageTemplate::getScenario, param.getScenario());
        queryWrapper.eq(StringUtils.isNotEmpty(param.getCreatorId()), MessageTemplate::getCreatorId, param.getCreatorId());
        queryWrapper.like(StringUtils.isNotEmpty(param.getSearch()), MessageTemplate::getTitle, param.getSearch());
        queryWrapper.eq(!Objects.isNull(param.getTtype()), MessageTemplate::getTtype, param.getTtype());
        queryWrapper.eq(StringUtils.isNotEmpty(param.getOrgId()), MessageTemplate::getOrgId, param.getOrgId());
        //默认按创建时间降序排序
        queryWrapper.orderByAsc(MessageTemplate::getCreatedDt);
        page = messageService.page(page, queryWrapper);
        List<MessageTemplate> records = page.getRecords();
        if (!CollUtil.isEmpty(records)) {
            records.forEach(it -> {
                if (StrUtil.isBlankIfStr(it.getCreatorId())) {
                    it.setCreator("超级管理员");
                } else {
                    UserDto user = userGrpcClient.getUser(it.getCreatorId());
                    it.setCreator(user.getName());
                }
            });
        }
        ResultPage<MessageTemplate> data = PageUtil.getResultPage(page.getCurrent(), page.getTotal(), page.getRecords());
        return XmResultJson.success(data);
    }

}